package com.qingyun.framework.web.service;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;


import com.qingyun.common.constant.Constants;
import com.qingyun.common.core.domain.model.LoginUser;
import com.qingyun.common.core.redis.RedisCache;
import com.qingyun.common.utils.ServletUtils;
import com.qingyun.common.utils.ip.AddressUtils;
import com.qingyun.common.utils.ip.IpUtils;

import com.qingyun.framework.config.properties.TokenProperties;
import com.qingyun.security.model.api.wxmp.AppUser;
import com.qingyun.security.model.shop.AppLoginUser;
import com.qingyun.security.model.tenant.TenantLoginUser;
import com.qingyun.security.model.tiktok.TikTokLoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService
{
	@Autowired
	private TokenProperties tokenProperties;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 30 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;

    /**
     * 获取系统超级管理员用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (Validator.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getSysTokenKey(uuid);
            LoginUser user = redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }
    /**
     * 获取微信用户身份信息
     *
     * @return 用户信息
     */
    public AppLoginUser getAppUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (Validator.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.APP_USER_KEY);
            String userKey = getAppTokenKey(uuid);
			AppLoginUser user = redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    public TikTokLoginUser getTikTokUser(HttpServletRequest request){
		// 获取请求携带的令牌
		String token = getToken(request);
		if (Validator.isNotEmpty(token))
		{
			Claims claims = parseToken(token);
			// 解析对应的权限以及用户信息
			String uuid = (String) claims.get(Constants.TIKTOK_USER_KEY);
			String userKey = getTiktokTokenKey(uuid);
			TikTokLoginUser user = redisCache.getCacheObject(userKey);
			return user;
		}
		return null;
	}



    /**
     * 设置用户身份信息
     */
    public void setLoginUser(Object loginUser)
    {

        if (Validator.isNotNull(loginUser) )
        {
            if(loginUser instanceof LoginUser){
                LoginUser adminUser = (LoginUser) loginUser;
                if (Validator.isNotEmpty(adminUser.getToken())) {
                    refreshToken(adminUser);
                }
            }else if(loginUser instanceof  AppLoginUser){
				AppLoginUser appLogin = (AppLoginUser) loginUser;
				if(Validator.isNotEmpty(appLogin.getToken())){
					appRefreshToken(appLogin);
				}
			}
            else if(loginUser instanceof TikTokLoginUser){
				TikTokLoginUser tikTokLoginUser=(TikTokLoginUser)loginUser;
				if (Validator.isNotEmpty(tikTokLoginUser.getToken())) {
					TiktokRefreshToken(tikTokLoginUser);
				}
			}

        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (Validator.isNotEmpty(token))
        {
            String userKey = getSysTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }


	/**
	 * 删除用户身份信息
	 */
	public void delAppUser(String token)
	{
		if (Validator.isNotEmpty(token))
		{
			String userKey = getAppTokenKey(token);
			redisCache.deleteObject(userKey);
		}
	}

	/**
	 * 删除抖音身份信息
	 */
	public void delTikTokLoginUser(String token)
	{
		if (Validator.isNotEmpty(token))
		{
			String userKey = getTiktokTokenKey(token);
			redisCache.deleteObject(userKey);
		}
	}


    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser)
    {
        String token = IdUtil.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims);
    }





    /**
     * 创建客户令牌
     * @param appLoginUser
     * @return
     */
    public String createAppToken(AppLoginUser appLoginUser)
    {
        String token = IdUtil.fastUUID();
        appLoginUser.setToken(token);
        appRefreshToken(appLoginUser);
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.APP_USER_KEY, token);
        return createToken(claims);
    }


	/**
	 * 创建抖音用户令牌
	 * @param tikTokLoginUser
	 * @return
	 */
	public String createTiktokUserToken(TikTokLoginUser tikTokLoginUser)
	{
		String token = IdUtil.fastUUID();
		tikTokLoginUser.setToken(token);
		TiktokRefreshToken(tikTokLoginUser);
		Map<String, Object> claims = new HashMap<>();
		claims.put(Constants.TIKTOK_USER_KEY, token);
		return createToken(claims);
	}


    /**
     * 验证令牌有效期，相差不足MILLIS_MINUTE_TEN分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }



    /**
     * 验证令牌有效期，相差不足MILLIS_MINUTE_TEN分钟，自动刷新缓存
     *
     * @param
     * @return 令牌
     */
    public void verifyAppToken(AppLoginUser appLoginUser)
    {
        long expireTime = appLoginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            appRefreshToken(appLoginUser);
        }
    }

	/**
	 * 验证令牌有效期，相差不足MILLIS_MINUTE_TEN分钟，自动刷新缓存
	 *
	 * @param
	 * @return 令牌
	 */
	public void verifyTikTokToken(TikTokLoginUser tikTokLoginUser)
	{
		long expireTime = tikTokLoginUser.getExpireTime();
		long currentTime = System.currentTimeMillis();
		if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
		{
			TiktokRefreshToken(tikTokLoginUser);
		}
	}

    /**
     * 管理员刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + tokenProperties.getExpireTime() * (60 * MILLIS_MINUTE));
        // 根据uuid将loginUser缓存
        String userKey = getSysTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, tokenProperties.getExpireTime(), TimeUnit.HOURS);
    }

    /**
     * 用户刷新令牌有效期
     *
     * @param appLoginUser 登录信息
     */
    public void appRefreshToken(AppLoginUser appLoginUser)
    {
		appLoginUser.setLoginTime(System.currentTimeMillis());
		appLoginUser.setExpireTime(appLoginUser.getLoginTime() + tokenProperties.getAppExpireTime() * (60 * MILLIS_MINUTE));
        // 根据uuid将loginUser缓存
        String userKey = getAppTokenKey(appLoginUser.getToken());
        redisCache.setCacheObject(userKey, appLoginUser, tokenProperties.getAppExpireTime(), TimeUnit.HOURS);
    }

	/**
	 * 抖音端刷新令牌有效期
	 *
	 * @param tikTokLoginUser 登录信息
	 */
	public void TiktokRefreshToken(TikTokLoginUser tikTokLoginUser)
	{
		tikTokLoginUser.setLoginTime(System.currentTimeMillis());
		tikTokLoginUser.setExpireTime(tikTokLoginUser.getLoginTime() + tokenProperties.getH5ExpireTime() * (60 * MILLIS_MINUTE));
		// 根据uuid将loginUser缓存
		String userKey = getTiktokTokenKey(tikTokLoginUser.getToken());
		redisCache.setCacheObject(userKey, tikTokLoginUser, tokenProperties.getH5ExpireTime(), TimeUnit.HOURS);
	}

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser)
    {
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOs().getName());
    }




    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, tokenProperties.getSecret()).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(tokenProperties.getSecret())
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(tokenProperties.getHeader());
        if (Validator.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey()
    {
        return Constants.LOGIN_TOKEN_KEY;
    }

    private String getSysTokenKey(String uuid){
    	return getTokenKey()+Constants.SYS_USER_KEY+uuid;
	}

    private String getAppTokenKey(String uuid){
    	return getTokenKey()+Constants.APP_USER_KEY+uuid;
	}

    private String getTiktokTokenKey(String uuid){
    	return getTokenKey()+Constants.TIKTOK_USER_KEY+uuid;
	}
}
